import {createRouter,createWebHistory} from "vue-router";
import { useUserStore } from "./stores/user";
import { ro } from "element-plus/es/locales.mjs";


const router = createRouter({
    history: createWebHistory(),
    routes:[
        {path:'/', component: () => import('./views/Home.vue')},
        {path:'/login', component: () => import('./views/Login.vue')},
        {path:'/register', component: () => import('./views/Register.vue')},
        {path:'/students', component: () => import('./views/StudentListView.vue')},
        {path:'/profile', 
            component: () => import('./views/StudentProfile.vue'),
            meta: {requiresAuth:true,role:'student'}
        },
        {path:'/students/edit/:id', 
            component: () => import('./views/StudentEdit.vue'),
            props: true,
            meta:{ requriesAuth:true,role:'teacher'}
        },
        { path: '/admin',component: () => import('./views/AdminDashboard.vue'),
            meta: { requiresAuth: true , role: 'admin'}
        },
        {
            path: '/teacher/profile/:id',
            component: () => import('./views/TeacherProfile.vue'),
            meta: {requiresAuth:true, role: 'teacher'}
        }
    ]
})



router.beforeEach((to,from,next) => {
    const userStore = useUserStore()
    if (to.meta.requiresAuth) {
        if (!userStore.isLoggedIn) {
            next('/login')
        }else if (to.meta.role && userStore.role !== to.meta.role) {
            next('/')
        }else {
            next()
        }
    } else {
        next()
    }
})


export default router